<template>
 <div class="home" style="height: 3000px;">
  <!-- <van-pull-refresh v-model="loading" @refresh="onRefresh">
  
</van-pull-refresh> -->

    <!-- 头部搜索框 -->
    <van-sticky>
      <van-search
        shape="round"
        background="#F00"
        placeholder="请输入搜索关键词"
        @click-input="$router.push('/search')"
        show-action
        >
        <!-- 左边图标 -->
        <template #left>
          <van-icon class="search-left" name="list-switch" size="30" @click="$router.push('./category')"/>
        </template>
        <!-- 右边 -->
        <template #action>
          <div class="searsh-login" @click="$router.push('./login')">登录</div>
        </template>
      </van-search>
    </van-sticky>

    <!-- 轮播图 -->
    <!-- <van-swipe :autoplay="3000" lazy-render>
      <van-swipe-item v-for="image in images" :key="image">
        <img :src="image" style="width: 100%; height: 100%;" />
      </van-swipe-item>
    </van-swipe> -->

    <!-- swiper -->
    <div class="swiper-container">
      <div class="swiper-wrapper">
          <div class="swiper-slide" v-for="banner in banners" :key="banner.id">
            <img :src="banner.image" style="width: 100%; height: 100%;" />
          </div>
      </div>
      <!-- 如果需要分页器 -->
      <div class="swiper-pagination"></div>
    </div>

    <!-- 宫格 -->
    <van-grid :column-num="5" :border="false">
      <van-grid-item 
      v-for="item in grids"
      :key="item.id"
      :icon="item.icon" 
      :text="item.title"
      :to="item.path"
      :border="true"
      />
    </van-grid>

    <!-- 秒杀专题 -->
    <div class="second-kill">
      <div class="title">
        <span>秒杀({{ currPeriod }}:00场):</span>
        <!-- 显示倒计时时间 -->
        <van-count-down :time="time">
          <template #default="timeData">
            <span class="block">{{ timeData.hours }}</span>
            <span class="colon">:</span>
            <span class="block">{{ timeData.minutes }}</span>
            <span class="colon">:</span>
            <span class="block">{{ timeData.seconds }}</span>
          </template>
        </van-count-down>
      </div>

      <!-- 秒杀商品列表 -->
      <div class="goods-list">
        <div
          class="goods-list-item"
          v-for="goods in secondKillGoods"
          :key="goods.id"
        >
          <img :src="goods.image" alt="" @click="$router.push('/detail?id=' + goods.id)"/>
          <span>价格: {{ goods.price }}</span>
        </div>
      </div>
    </div>

    <!-- 推荐商品列表 -->
    <van-divider class="divider">推荐商品</van-divider>
    <!-- 下拉加载更多列表 -->
    <van-list
      v-model:loading="loading"
      :finished="isEnd"
      finished-text="已经到底了！"
      offset="500"
      @load="loadGoods"
      :immediate-check="false"
    >
      <div class="recommend">
        <div 
          class="recommend-item"
          v-for="goods in goodsList"
          :key="goods.id"
          @click="$router.push('/detail?id=' + goods.id)"
        >
          <img :src="goods.image" alt="">
          <div class="title van-multi-ellipsis--l2">{{ goods.title }}</div>
          <div class="price">
            <span class="price-curr">￥{{ goods.price }}</span>
            <span class="price-origin">原价：{{ goods.originPrice }}</span>
          </div>
          <div>
            <van-button 
              type="primary" 
              size="mini"
              @click.stop="handleAdd(goods)"
            >加入购物车</van-button>
          </div>
        </div>
      </div>
    </van-list>
    <!-- 回到顶部 -->
    <van-back-top :bottom="100" :offset="800"/>
  </div>
</template>

<script>
// 引入swiper
import Swiper from 'swiper/swiper-bundle'
import 'swiper/swiper-bundle.css'
import { showSuccessToast } from 'vant'

// 导入API方法
import {getBanners, getGoods} from '../../api/home'
// 获取图片地址方法
function getImageUrl(name) {
  return new URL(`../../assets/${name}.png`, import.meta.url).href
}
export default {
 name: 'Home',
 data() {
    return {
      //loading: false, // 是否正在下拉刷新
      banners: [], // 轮播图数据
      goodsList: [], // 推荐商品列表数据
      grids: [
        {title: '好运超市', icon: getImageUrl('1'), path: '/category'},
        {title: '服饰美妆', icon: getImageUrl('2'), path: '/category'},
        {title: '数码3c', icon: getImageUrl('3'), path: '/category'},
        {title: '充值中心', icon: getImageUrl('4'), path: '/category'},
        {title: '优选会员', icon: getImageUrl('5'), path: '/category'},
      ],
      time: 2 * 60 * 60 * 1000, // 秒杀倒计时的总时长，单位为毫秒
      currPeriod: 0, // 当前秒杀场次的小时数
      periods: [0, 8, 10, 14, 15, 18, 24], // 保存每天各秒杀场次的小时数
      nextIndex: 0, // 推荐商品列表分页查询时，下一页数据起始索引
      isEnd: false, // 是否所有推荐商品的数据全部查询结束
      loading: false, // 是否正在加载更多商品数据中
    }
 },
 computed: {
    // 随机生成几件秒杀商品的数据
    secondKillGoods() {
      const result = []
      const len = this.goodsList.length
      for(let i = 0; i < 6; i++) {
        const randIndex = Math.floor(Math.random() * len)
        result.push({
          ...this.goodsList[randIndex]
        })
      }
      return result
    },
  },
  // nextTick 钩子函数 轮播
  async created() {
    // 秒杀相关
    this.caclSecondKillTime()
    const {banners, items} = await getBanners()
    this.banners = banners
    this.goodsList = items.list
    this.nextIndex = items.nextIndex
    this.isEnd = items.isEnd
    this.$nextTick(() => {
      // console.log('home nextTick...')
      // 创建 Swiper 对象实例
      new Swiper ('.swiper-container', {
        loop: true, // 循环模式选项
        autoplay: true,
        effect: 'fade', // 淡入淡出轮播
        // 如果需要分页器
        pagination: {
          el: '.swiper-pagination',
        },
      })
    })
  },
  methods: {
    // 计算秒杀倒计时
    caclSecondKillTime() {
      // 获取当前系统时间
      const currentTime = new Date()
      // 获取当前时间的小时数
      const currentHour = currentTime.getHours()
      // 查找出当前小时数落在哪两个秒杀场次范围内
      // 将下一次场次的小时数在数组中的元素下标返回
      const nextIndex = this.periods.findIndex(period => period > currentHour)
      // 设置当前场次小时数
      this.currPeriod = this.periods[nextIndex - 1]
      /* 计算倒计时时间毫秒值 */
      // 当前系统时间毫秒值
      const currMills = currentTime.getTime()
      // 修改日期时间对象中的小时分钟秒数和毫秒值，以算出下一场起始时间
      currentTime.setHours(this.periods[nextIndex])
      currentTime.setMinutes(0)
      currentTime.setSeconds(0)
      currentTime.setMilliseconds(0)
      const nextMills = currentTime.getTime()
      // 计算两个毫秒差值
      this.time = nextMills - currMills
    },
    // 触底加载更多推荐商品
    async loadGoods(){
      const {list, isEnd, nextIndex} = await getGoods(this.nextIndex)
      // console.log(list, isEnd, nextIndex)
      this.goodsList = [
        ...this.goodsList,
        ...list,
      ]
      this.nextIndex = nextIndex
      this.isEnd = isEnd
      this.loading = false
    },
    // 加入购物车按钮
    handleAdd(goods){
      const {id, title, price, image} = goods
      const currGoods = {id, title, price, image}
      this.$store.commit('shoppingCart/addCart', currGoods)
      showSuccessToast({
        message: '加入成功',
        duration: 1000
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.search-left{
  color: #fff;
  margin-right: 12px;
}
.searsh-login{
  color: #fff;
  font-size: 16px;
}

// 秒杀商品
.colon {
    display: inline-block;
    margin: 0 4px;
    color: red;
  }
  .block {
    display: inline-block;
    width: 22px;
    color: #fff;
    font-size: 12px;
    text-align: center;
    background-color: red;
  }
.second-kill {
  .title{
    display: flex;
    align-items: center;
    margin-bottom: 5px;
  }
  .goods-list {
    display: flex;
    width: 100%;
    overflow-x: auto;

    &-item {
      display: flex;
      flex-direction: column;
      margin-right: 6px;

      img {
        width: 120px;
        height: 120px;
      }

      span {
        color: red;
        font-size: 18px;
        font-weight: 700;
      }
    }
  }
}

// 推荐商品
.divider{
  font-size: 18px;
  margin: 20px 0;
  color: black;
  font-weight: 700;
}
.recommend{
  display: flex;
  flex-wrap: wrap;
  justify-content: center;

  &-item{
    width: 46%;
    padding: 6px;
    img{
      width: 95%;
      height: 180px;
    }
  }
  .price-curr{
    color: red;
    margin-right: 10px;
    font-weight: 700;
  }
  .price-origin{
    color: lightgrey;
    text-decoration: line-through;
    font-size: 12px;
  }
}
</style>
